package GUI;

import util.User;
import util.UserDAO;
import util.TravelRecordDAO;
import util.ThemeManager;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * 碳减排统计面板，用于展示用户碳减排数据和排行榜
 */
public class CarbonReductionPanel extends JPanel {
    private User currentUser;
    private JTable rankingTable;
    private DefaultTableModel tableModel;
    private JLabel totalCarbonReductionLabel;
    private JLabel userRankingLabel;
    private JLabel userCarbonReductionLabel;
    private JPanel mainPanel;

    public CarbonReductionPanel(User user) {
        this.currentUser = user;

        // 设置布局
        setLayout(new BorderLayout(0, 0));
        setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        setBackground(ThemeManager.getColor(ThemeManager.BACKGROUND_COLOR));

        // 创建内容面板
        mainPanel = new JPanel(new BorderLayout(20, 20));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(30, 40, 30, 40));
        mainPanel.setBackground(ThemeManager.getColor(ThemeManager.BACKGROUND_COLOR));

        // 创建主内容面板（使用网格包布局）
        JPanel contentPanel = new JPanel(new GridBagLayout());
        contentPanel.setOpaque(false);
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.BOTH;
        constraints.insets = new Insets(0, 0, 0, 0);

        // 创建用户碳减排信息面板
        JPanel userInfoPanel = createUserInfoPanel();
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.weightx = 1.0;
        constraints.weighty = 0.2; // 减小高度比例(原为0.3)
        constraints.insets = new Insets(0, 0, 20, 0);
        contentPanel.add(userInfoPanel, constraints);

        // 创建排行榜面板
        JPanel rankingPanel = createRankingPanel();
        constraints.gridx = 0;
        constraints.gridy = 1;
        constraints.weightx = 1.0;
        constraints.weighty = 0.8; // 增加高度比例(原为0.7)
        constraints.insets = new Insets(0, 0, 0, 0);
        contentPanel.add(rankingPanel, constraints);

        mainPanel.add(contentPanel, BorderLayout.CENTER);
        add(mainPanel, BorderLayout.CENTER);

        // 加载数据
        loadRankingData();
        loadTotalCarbonReduction();
    }

    /**
     * 创建用户碳减排信息面板
     */
    private JPanel createUserInfoPanel() {
        JPanel panel = new JPanel(new BorderLayout(20, 0));
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(ThemeManager.getColor(ThemeManager.BORDER_COLOR), 1, true),
                BorderFactory.createEmptyBorder(25, 30, 25, 30)));
        panel.setBackground(ThemeManager.getColor(ThemeManager.PANEL_BACKGROUND_COLOR));

        // 创建左侧信息面板
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        infoPanel.setOpaque(false);
        infoPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

        // 面板标题
        JLabel panelTitleLabel = new JLabel("我的碳减排统计");
        panelTitleLabel.setFont(new Font("等线", Font.BOLD, 22));
        panelTitleLabel.setForeground(ThemeManager.getColor(ThemeManager.PRIMARY_COLOR));
        panelTitleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        panelTitleLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
        infoPanel.add(panelTitleLabel);

        // 用户碳减排量
        JPanel userCarbonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 5));
        userCarbonPanel.setOpaque(false);
        userCarbonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel userCarbonLabelText = new JLabel("您的碳减排量：");
        userCarbonLabelText.setFont(new Font("等线", Font.PLAIN, 16));
        userCarbonLabelText.setForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));
        userCarbonPanel.add(userCarbonLabelText);

        userCarbonReductionLabel = new JLabel(String.format("%.2f kg", currentUser.getCarbonReduction()));
        userCarbonReductionLabel.setFont(new Font("等线", Font.BOLD, 22));
        userCarbonReductionLabel.setForeground(ThemeManager.getColor(ThemeManager.SUCCESS_COLOR));
        userCarbonPanel.add(userCarbonReductionLabel);

        infoPanel.add(userCarbonPanel);
        infoPanel.add(Box.createVerticalStrut(15));

        // 用户排名
        JPanel userRankPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 5));
        userRankPanel.setOpaque(false);
        userRankPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel userRankLabelText = new JLabel("您在所有用户中的排名：");
        userRankLabelText.setFont(new Font("等线", Font.PLAIN, 16));
        userRankLabelText.setForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));
        userRankPanel.add(userRankLabelText);

        userRankingLabel = new JLabel("加载中...");
        userRankingLabel.setFont(new Font("等线", Font.BOLD, 22));
        userRankingLabel.setForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));
        userRankPanel.add(userRankingLabel);

        infoPanel.add(userRankPanel);
        infoPanel.add(Box.createVerticalStrut(15));

        // 总碳减排量
        JPanel totalCarbonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 5));
        totalCarbonPanel.setOpaque(false);
        totalCarbonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel totalCarbonLabelText = new JLabel("全部用户总碳减排量：");
        totalCarbonLabelText.setFont(new Font("等线", Font.PLAIN, 16));
        totalCarbonLabelText.setForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));
        totalCarbonPanel.add(totalCarbonLabelText);

        totalCarbonReductionLabel = new JLabel("加载中...");
        totalCarbonReductionLabel.setFont(new Font("等线", Font.BOLD, 22));
        totalCarbonReductionLabel.setForeground(ThemeManager.getColor(ThemeManager.ACCENT_COLOR));
        totalCarbonPanel.add(totalCarbonReductionLabel);

        infoPanel.add(totalCarbonPanel);

        // 左边放infoPanel
        panel.add(infoPanel, BorderLayout.WEST);

        // 右边放计算说明
        JPanel descriptionPanel = new JPanel(new BorderLayout());
        descriptionPanel.setOpaque(false);
        descriptionPanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 0));

        JLabel descTitle = new JLabel("碳减排计算方式");
        descTitle.setFont(new Font("等线", Font.BOLD, 16));
        descTitle.setForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));
        descriptionPanel.add(descTitle, BorderLayout.NORTH);

        JPanel rulesPanel = new JPanel();
        rulesPanel.setLayout(new BoxLayout(rulesPanel, BoxLayout.Y_AXIS));
        rulesPanel.setOpaque(false);
        rulesPanel.setBorder(BorderFactory.createEmptyBorder(15, 0, 0, 0));

        String[] rules = {
                "- 骑行共享单车/自行车：每公里减少0.2kg碳排放",
                "- 乘坐公交/地铁：每次减少0.5kg碳排放",
                "- 步行：每公里减少0.2kg碳排放"
        };

        for (String rule : rules) {
            JLabel ruleLabel = new JLabel(rule);
            ruleLabel.setFont(new Font("等线", Font.PLAIN, 14));
            ruleLabel.setForeground(ThemeManager.getColor(ThemeManager.SECONDARY_TEXT_COLOR));
            ruleLabel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
            rulesPanel.add(ruleLabel);
        }

        descriptionPanel.add(rulesPanel, BorderLayout.CENTER);

        // 添加环保小贴士
        JLabel tipLabel = new JLabel("<html>小贴士：选择低碳出行方式不仅能减少碳排放，<br>还能获得积分奖励，为环保贡献力量！</html>");
        tipLabel.setFont(new Font("等线", Font.ITALIC, 14));
        tipLabel.setForeground(ThemeManager.getColor(ThemeManager.SECONDARY_TEXT_COLOR));
        tipLabel.setBorder(BorderFactory.createEmptyBorder(15, 0, 0, 0));
        descriptionPanel.add(tipLabel, BorderLayout.SOUTH);

        panel.add(descriptionPanel, BorderLayout.EAST);

        return panel;
    }

    /**
     * 创建排行榜面板
     */
    private JPanel createRankingPanel() {
        JPanel panel = new JPanel(new BorderLayout(0, 20));
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(ThemeManager.getColor(ThemeManager.BORDER_COLOR), 1, true),
                BorderFactory.createEmptyBorder(25, 30, 25, 30)));
        panel.setBackground(ThemeManager.getColor(ThemeManager.PANEL_BACKGROUND_COLOR));

        // 排行榜标题
        JLabel rankingTitle = new JLabel("碳减排排行榜");
        rankingTitle.setFont(new Font("等线", Font.BOLD, 22));
        rankingTitle.setForeground(ThemeManager.getColor(ThemeManager.PRIMARY_COLOR));
        panel.add(rankingTitle, BorderLayout.NORTH);

        // 创建表格面板
        JPanel tablePanel = new JPanel(new BorderLayout(0, 0));
        tablePanel.setOpaque(false);

        // 创建表格模型
        tableModel = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 使表格不可编辑
            }

            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex == 0)
                    return Integer.class; // 排名列
                if (columnIndex == 3)
                    return Double.class; // 碳减排量列
                return String.class;
            }
        };

        // 添加列
        tableModel.addColumn("排名");
        tableModel.addColumn("用户名");
        tableModel.addColumn("姓名");
        tableModel.addColumn("碳减排量(kg)");

        // 创建表格
        rankingTable = new JTable(tableModel);
        rankingTable.setFont(new Font("等线", Font.PLAIN, 15));
        rankingTable.setRowHeight(35);
        rankingTable.setShowGrid(true);
        rankingTable.setShowHorizontalLines(true);
        rankingTable.setShowVerticalLines(true);
        rankingTable.setGridColor(ThemeManager.getColor(ThemeManager.BORDER_COLOR));
        rankingTable.getTableHeader().setFont(new Font("等线", Font.BOLD, 16));
        rankingTable.getTableHeader().setReorderingAllowed(false);
        rankingTable.getTableHeader().setBackground(ThemeManager.getColor(ThemeManager.TABLE_HEADER_COLOR));
        rankingTable.getTableHeader().setForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));
        rankingTable.setSelectionBackground(ThemeManager.getColor(ThemeManager.TABLE_SELECTION_COLOR));
        rankingTable.setSelectionForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));
        rankingTable.setBackground(ThemeManager.getColor(ThemeManager.PANEL_BACKGROUND_COLOR));
        rankingTable.setForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));
        rankingTable.setFillsViewportHeight(true);

        // 设置表格列的渲染器
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        rankingTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);

        DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
        rightRenderer.setHorizontalAlignment(JLabel.RIGHT);
        rankingTable.getColumnModel().getColumn(3).setCellRenderer(rightRenderer);

        // 设置列宽
        rankingTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        rankingTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        rankingTable.getColumnModel().getColumn(2).setPreferredWidth(120);
        rankingTable.getColumnModel().getColumn(3).setPreferredWidth(150);

        // 创建滚动面板并添加表格
        JScrollPane scrollPane = new JScrollPane(rankingTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.getViewport().setBackground(ThemeManager.getColor(ThemeManager.PANEL_BACKGROUND_COLOR));
        tablePanel.add(scrollPane, BorderLayout.CENTER);

        panel.add(tablePanel, BorderLayout.CENTER);

        // 创建底部面板和刷新按钮
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setOpaque(false);
        bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));

        // 添加提示文本
        JLabel tipLabel = new JLabel("排行榜每天更新一次，努力提高您的排名吧！");
        tipLabel.setFont(new Font("等线", Font.ITALIC, 14));
        tipLabel.setForeground(ThemeManager.getColor(ThemeManager.SECONDARY_TEXT_COLOR));
        bottomPanel.add(tipLabel, BorderLayout.WEST);

        // 创建刷新按钮
        JButton refreshButton = new JButton("刷新排行榜");
        refreshButton.setFont(new Font("等线", Font.BOLD, 14));
        refreshButton.setForeground(ThemeManager.getColor(ThemeManager.BUTTON_TEXT_COLOR));
        refreshButton.setBackground(ThemeManager.getColor(ThemeManager.PRIMARY_COLOR));
        refreshButton.setFocusPainted(false);
        refreshButton.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(0, 100, 0), 1),
                BorderFactory.createEmptyBorder(8, 15, 8, 15)));
        refreshButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        refreshButton.addActionListener(e -> {
            loadRankingData();
            loadTotalCarbonReduction();
        });

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        buttonPanel.setOpaque(false);
        buttonPanel.add(refreshButton);
        bottomPanel.add(buttonPanel, BorderLayout.EAST);

        panel.add(bottomPanel, BorderLayout.SOUTH);

        return panel;
    }

    /**
     * 加载排行榜数据
     */
    public void loadRankingData() {
        // 清空表格
        tableModel.setRowCount(0);

        UserDAO userDAO = new UserDAO();
        List<User> ranking = userDAO.getCarbonReductionRanking();

        int userRank = -1;

        for (int i = 0; i < ranking.size(); i++) {
            User user = ranking.get(i);
            tableModel.addRow(new Object[] {
                    i + 1,
                    user.getUsername(),
                    user.getName(),
                    user.getCarbonReduction()
            });

            if (user.getId() == currentUser.getId()) {
                userRank = i + 1;
                // 高亮显示当前用户的行
                final int row = i;
                SwingUtilities.invokeLater(() -> {
                    rankingTable.setRowSelectionInterval(row, row);
                });
            }
        }

        // 更新用户排名
        if (userRank != -1) {
            userRankingLabel.setText("第 " + userRank + " 名");
        } else {
            userRankingLabel.setText("未上榜");
        }
    }

    /**
     * 加载总碳减排量
     */
    public void loadTotalCarbonReduction() {
        TravelRecordDAO recordDAO = new TravelRecordDAO();
        double totalReduction = recordDAO.getTotalCarbonReduction();
        totalCarbonReductionLabel.setText(String.format("%.2f kg", totalReduction));
    }

    /**
     * 更新主题
     */
    public void updateTheme() {
        // 更新面板背景
        setBackground(ThemeManager.getColor(ThemeManager.BACKGROUND_COLOR));
        mainPanel.setBackground(ThemeManager.getColor(ThemeManager.BACKGROUND_COLOR));

        // 更新表格样式
        rankingTable.setBackground(ThemeManager.getColor(ThemeManager.PANEL_BACKGROUND_COLOR));
        rankingTable.setForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));
        rankingTable.setSelectionBackground(ThemeManager.getColor(ThemeManager.TABLE_SELECTION_COLOR));
        rankingTable.setSelectionForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));
        rankingTable.setGridColor(ThemeManager.getColor(ThemeManager.BORDER_COLOR));
        rankingTable.getTableHeader().setBackground(ThemeManager.getColor(ThemeManager.TABLE_HEADER_COLOR));
        rankingTable.getTableHeader().setForeground(ThemeManager.getColor(ThemeManager.TEXT_COLOR));

        // 刷新UI
        SwingUtilities.updateComponentTreeUI(this);
        repaint();
    }
}
